package org.linphone.setup;

/*
 LoginActivity.java
 Copyright (C) 2012  Belledonne Communications, Grenoble, France

 getActivity() program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.

 getActivity() program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with getActivity() program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;
import org.linphone.LinphoneActivity;
import org.linphone.LinphoneLauncherActivity;
import com.leehuubsd.yiyanzb.R;
import org.linphone.activity.New_Login_vCode;
import org.linphone.activity.New_Reg;
import org.linphone.activity.New_Reg_EditePassword;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

/**
 * @author Sylvain Berfini
 */
public class GenericLoginFragment extends Fragment implements OnClickListener {
	private EditText login, password;
	private SharedPreferences sharedPreferences;
	private Editor edit;
	private String logindate, domain, OEMID;
	private Button btn_longin, btn_pay, Button01;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.setup_generic_login, container,
				false);

		login = (EditText) view.findViewById(R.id.setup_username);
		password = (EditText) view.findViewById(R.id.setup_password);
		btn_longin = (Button) view.findViewById(R.id.btn_longin);
		btn_pay = (Button) view.findViewById(R.id.btn_pay);
		Button01 = (Button) view.findViewById(R.id.Button01);
		btn_longin.setOnClickListener(this);
		btn_pay.setOnClickListener(this);
		Button01.setOnClickListener(this);
		sharedPreferences = getActivity().getSharedPreferences("bosideng",
				Context.MODE_WORLD_READABLE);
		edit = sharedPreferences.edit();
		OEMID = getActivity().getResources().getString(R.string.oem);

		return view;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_longin:
			String id = login.getText().toString();
			String pwd = password.getText().toString();
			if (!TextUtils.isEmpty(id) && !TextUtils.isEmpty(pwd)) {
				GetPostDate("/YXBp/dm9zb2Vt/TG9nb24PQ", id, pwd);
			} else {
				Show_Toast("请输入正确的账号或密码");
			}
			break;
		case R.id.btn_pay:
			Intent i = new Intent(getActivity(), New_Reg.class);
			startActivity(i);
			break;
		case R.id.Button01:
			Intent intent = new Intent(getActivity(), New_Reg_EditePassword.class);
			startActivity(intent);
			break;

		default:
			break;
		}
	}


	public void Show_Toast(String str) {
		Toast.makeText(getActivity(), str, Toast.LENGTH_SHORT).show();
	}

	String ProgressMsg = "";
	static ProgressDialog m_Dialog;
	MyCount mc;
	AlertDialog dlg;

	private void GetPostDate(final String Path, final String UserPhone,
			final String Upwd) {

		String ProgressMsg = "正在登录，请稍后……";
		m_Dialog = ProgressDialog.show(getActivity(), "", ProgressMsg, true);
		m_Dialog.setIcon(android.R.drawable.ic_lock_idle_alarm);
		mc = new MyCount(30000, 1000);
		mc.start();
		RequestQueue queue = Volley.newRequestQueue(getActivity());
		StringRequest request = new StringRequest(Method.POST, getResources()
				.getString(R.string.http) + Path, new Listener<String>() {

			@Override
			public void onResponse(String arg0) {
				// TODO Auto-generated method stub
				System.out.println(arg0);
				m_Dialog.dismiss();
				mc.cancel();
				JSONObject object;
				try {
					object = new JSONObject(arg0);
					int i = object.getInt("retCode");
					if (i == 0) {
						if (object.getBoolean("isValidate")) {
							Show_Toast("登陆成功");
							String serverip = object.getString("serverip");
							int port = object.getInt("port");
							domain = serverip;
							edit.putString("Phone", login.getText().toString());
							edit.putString("CardPassWord", password.getText().toString());
							edit.putString("serverip", serverip);
							edit.putInt("port", port);
							edit.commit();
							if (login.getText() == null || login.length() == 0
									|| password.getText() == null
									|| password.length() == 0) {
								Toast.makeText(
										getActivity(),
										getString(R.string.first_launch_no_login_password),
										Toast.LENGTH_LONG).show();
								return;
							} else {
								
								SetupActivity.instance().genericLogIn(
										OEMID + "-"
												+ login.getText().toString(),
										password.getText().toString(), domain);
								startActivity(new Intent().setClass(getActivity(), LinphoneActivity.class));
								SetupActivity.instance().finish();
							}
						} else {
							Show_Toast("请验证手机号");
							Intent intent = new Intent(getActivity(),
									New_Login_vCode.class);
							intent.putExtra("UserPhone", UserPhone);
							intent.putExtra("Upwd", Upwd);
							startActivity(intent);

						}
						// 请求成功。等待短信即可！
					} else {
						// 请求失败，查看提示内容
						String s = object.getString("exception");
						Toast.makeText(getActivity(),
								s + "(" + object.getInt("retCode") + ")",
								Toast.LENGTH_SHORT).show();
					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}, new com.android.volley.Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError arg0) {
				// TODO Auto-generated method stub
				m_Dialog.dismiss();
				mc.cancel();
				Show_Toast("服务器忙，请稍后尝试登陆…");
			}
		}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				// TODO Auto-generated method stub
				String p = encryptBASE64(UserPhone);
				Map<String, String> map = new HashMap<String, String>();
				map.put("dXNlck5hbWUPQ", p);
				map.put("password", Upwd);
				map.put("proxyId", OEMID);
				return map;
			}
		};
		queue.add(request);
	}

	class MyCount extends CountDownTimer {

		public MyCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}

		public void onFinish() {
			try {
				m_Dialog.dismiss();
			} catch (Exception e) {
			}
		}

		public void onTick(long millisUntilFinished) {
			long a = millisUntilFinished / 1000;
			m_Dialog.setMessage(ProgressMsg + "（" + (30 - a) + " 秒）");
		}
	}

	/**
	 * BASE64 加密
	 * 
	 * @param str
	 * @return
	 */
	@SuppressLint("NewApi")
	public String encryptBASE64(String str) {
		if (str == null || str.length() == 0) {
			return null;
		}
		try {
			byte[] encode = str.getBytes("UTF-8");
			// base64 加密

			String s = new String(Base64.encode(encode, 0, encode.length,
					Base64.DEFAULT), "UTF-8");
			String s1 = s.replaceAll("=", "PQ");
			Log.i("LOL", s1);
			return s1;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return null;
	}
	
	

}
